<template>
  <div class="codes-container">
    <el-card class="codes-card">
      <div class="header-section">
        <h2>Exchange Code Management</h2>
        <el-button type="primary" @click="showGenerateDialog">Generate Codes</el-button>
      </div>
      
      <!-- Search and Filter -->
      <div class="filter-section">
        <el-input 
          v-model="searchQuery" 
          placeholder="Search codes..." 
          prefix-icon="Search"
          style="max-width: 300px; margin-right: 15px;"
        />
        <el-select v-model="filterStatus" placeholder="Filter by status" style="max-width: 200px;">
          <el-option label="All" value=""></el-option>
          <el-option label="Active" value="ACTIVE"></el-option>
          <el-option label="Expired" value="EXPIRED"></el-option>
          <el-option label="Used" value="USED"></el-option>
        </el-select>
      </div>
      
      <!-- Codes Table -->
      <el-table 
        :data="filteredCodes" 
        style="width: 100%; margin-top: 20px;" 
        v-loading="loading"
      >
        <el-table-column prop="code" label="Code" width="150"></el-table-column>
        <el-table-column prop="description" label="Description"></el-table-column>
        <el-table-column prop="expirationDate" label="Expiration Date" width="150"></el-table-column>
        <el-table-column prop="status" label="Status" width="120">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.status)"
              disable-transitions
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="150">
          <template #default="scope">
            <el-button size="small" @click="viewCodeDetails(scope.row)">View</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteCode(scope.row)"
              v-if="scope.row.status !== 'USED'"
            >
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Pagination -->
      <div class="pagination-section">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredCodes.length"
        />
      </div>
    </el-card>
    
    <!-- Generate Codes Dialog -->
    <el-dialog title="Generate Exchange Codes" v-model="generateDialogVisible" width="500px">
      <el-form :model="generateForm" :rules="generateRules" ref="generateFormRef" label-width="150px">
        <el-form-item label="Number of Codes" prop="count">
          <el-input-number v-model="generateForm.count" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="Code Prefix" prop="prefix">
          <el-input v-model="generateForm.prefix" placeholder="Optional prefix"></el-input>
        </el-form-item>
        <el-form-item label="Expiration Date" prop="expirationDate">
          <el-date-picker
            v-model="generateForm.expirationDate"
            type="date"
            placeholder="Select expiration date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="Description" prop="description">
          <el-input 
            v-model="generateForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="Enter description for these codes"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="generateDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="generateCodes">Generate</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- Code Details Dialog -->
    <el-dialog title="Code Details" v-model="detailsDialogVisible" width="600px">
      <div v-if="selectedCode">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="Code">
            {{ selectedCode.code }}
          </el-descriptions-item>
          <el-descriptions-item label="Description">
            {{ selectedCode.description }}
          </el-descriptions-item>
          <el-descriptions-item label="Status">
            <el-tag :type="getStatusType(selectedCode.status)" disable-transitions>
              {{ selectedCode.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Created Date">
            {{ selectedCode.createdDate }}
          </el-descriptions-item>
          <el-descriptions-item label="Expiration Date">
            {{ selectedCode.expirationDate }}
          </el-descriptions-item>
          <el-descriptions-item label="Used Date" v-if="selectedCode.usedDate">
            {{ selectedCode.usedDate }}
          </el-descriptions-item>
          <el-descriptions-item label="Used By" v-if="selectedCode.usedBy">
            {{ selectedCode.usedBy }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailsDialogVisible = false">Close</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, computed } from 'vue'

export default {
  name: 'MerchantCodes',
  setup() {
    const loading = ref(false)
    const generateDialogVisible = ref(false)
    const detailsDialogVisible = ref(false)
    const selectedCode = ref(null)
    
    const searchQuery = ref('')
    const filterStatus = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // Mock data for exchange codes
    const codes = ref([
      {
        code: 'EXC123456',
        description: 'Black Friday Special Offer',
        expirationDate: '2024-12-31',
        status: 'ACTIVE',
        createdDate: '2023-10-01',
        usedDate: null,
        usedBy: null
      },
      {
        code: 'EXC789012',
        description: 'New Customer Welcome',
        expirationDate: '2024-06-30',
        status: 'EXPIRED',
        createdDate: '2023-05-15',
        usedDate: null,
        usedBy: null
      },
      {
        code: 'EXC345678',
        description: 'VIP Customer Reward',
        expirationDate: '2024-08-15',
        status: 'USED',
        createdDate: '2023-07-20',
        usedDate: '2023-07-25',
        usedBy: 'Customer #1001'
      }
    ])
    
    const generateForm = reactive({
      count: 1,
      prefix: '',
      expirationDate: '',
      description: ''
    })
    
    const generateRules = {
      count: [
        { required: true, message: 'Please enter number of codes to generate', trigger: 'blur' }
      ],
      expirationDate: [
        { required: true, message: 'Please select expiration date', trigger: 'change' }
      ],
      description: [
        { required: true, message: 'Please enter description', trigger: 'blur' }
      ]
    }
    
    const filteredCodes = computed(() => {
      let result = codes.value
      
      // Apply search filter
      if (searchQuery.value) {
        result = result.filter(code => 
          code.code.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
          code.description.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
      }
      
      // Apply status filter
      if (filterStatus.value) {
        result = result.filter(code => code.status === filterStatus.value)
      }
      
      // Apply pagination
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return result.slice(start, end)
    })
    
    const showGenerateDialog = () => {
      Object.assign(generateForm, {
        count: 1,
        prefix: '',
        expirationDate: '',
        description: ''
      })
      generateDialogVisible.value = true
    }
    
    const generateCodes = async () => {
      // In a real application, you would make an API call to generate codes
      // For now, using a mock implementation
      try {
        loading.value = true
        
        // Generate the requested number of codes
        for (let i = 0; i < generateForm.count; i++) {
          const newCode = {
            code: generateForm.prefix + Math.random().toString(36).substring(2, 10).toUpperCase(),
            description: generateForm.description,
            expirationDate: generateForm.expirationDate,
            status: 'ACTIVE',
            createdDate: new Date().toISOString().split('T')[0],
            usedDate: null,
            usedBy: null
          }
          codes.value.push(newCode)
        }
        
        ElMessage.success(`${generateForm.count} codes generated successfully!`)
        generateDialogVisible.value = false
      } catch (error) {
        console.error('Generate codes error:', error)
        ElMessage.error('An error occurred while generating codes')
      } finally {
        loading.value = false
      }
    }
    
    const viewCodeDetails = (code) => {
      selectedCode.value = code
      detailsDialogVisible.value = true
    }
    
    const deleteCode = (code) => {
      ElMessageBox.confirm(
        `Are you sure you want to delete the code "${code.code}"?`,
        'Confirm Delete',
        {
          confirmButtonText: 'Delete',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      ).then(() => {
        const index = codes.value.findIndex(c => c.code === code.code)
        if (index !== -1) {
          codes.value.splice(index, 1)
          ElMessage.success('Code deleted successfully!')
        }
      }).catch(() => {
        // User cancelled
      })
    }
    
    const getStatusType = (status) => {
      switch (status) {
        case 'ACTIVE': return 'success'
        case 'EXPIRED': return 'danger'
        case 'USED': return 'info'
        default: return 'info'
      }
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    return {
      loading,
      generateDialogVisible,
      detailsDialogVisible,
      selectedCode,
      searchQuery,
      filterStatus,
      currentPage,
      pageSize,
      codes,
      generateForm,
      generateRules,
      filteredCodes,
      showGenerateDialog,
      generateCodes,
      viewCodeDetails,
      deleteCode,
      getStatusType,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.codes-container {
  padding: 20px;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.codes-card {
  padding: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.pagination-section {
  margin-top: 20px;
  text-align: center;
}
</style>